package mspdt.ubzuuch.mn;

import java.text.NumberFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AutomobileActivity extends Activity {

	private ArrayList<String> titles = new ArrayList<String>();
	private ArrayList<String> bodys = new ArrayList<String>();
	private ArrayList<String> prices = new ArrayList<String>();
	private ArrayList<String> images = new ArrayList<String>();
	private ArrayList<Integer> ids = new ArrayList<Integer>();
	private ListView list;
	private ListAdapter adapter;
	private int[] factory_keys={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,35,36,37,48,49};
	private String[] factory_names = {"Acura", "Audi", "BMW", "Chevrolet", "Chrysler", "Daewoo", "Daihatsu", "Dodge", "GMC", "Great Wall", "Honda", "Hummer","Hyundai",
			"Infiniti", "Isuzu", "Jaguar","Jeep","Kia","Land Rover","Lexus","Lincoln","Mazda","Mercedes Benz","Mercury","Mitsubishi","Nissan","Porsche",
			"Renault","Skoda","Ssang Yong","Subaru","Toyota","Volkswagen","Volvo","Орос","Бусад"};
	private int tv_id = R.id.title_menu_5;
	private NetworkConnectionClass network;
	private int page = 1;
	private boolean scrollable = false;
	private ProgressBar progress;
  	@Override
	public void onBackPressed() {
	   finish();
	   overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_automobile);
		network=new NetworkConnectionClass(this);
		progress = (ProgressBar)findViewById(R.id.car_view_progress);
		progress.setVisibility(View.GONE);
		list=(ListView)findViewById(R.id.car_view_list);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutomobileActivity.this, AutoViewActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("title", tv_id);
				bundle.putInt("id", ids.get(arg2));
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.no_anim);
			}
		});
		list.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				final int lastItem = firstVisibleItem + visibleItemCount;
	            if(lastItem == totalItemCount) {
	                // Last item is fully visible.
	            	if(scrollable)
	            	{
	            		progress.setVisibility(View.VISIBLE);
	            		scrollable=false;
	            		loadPageData(page);
	            		Log.d("TEST", "1");
	            	}
	            	else
	            	{
	            		Log.d("TEST", "2");
	            	}
	            	
	            }
			}
		});
		createTitleComponents();
		findViewById(R.id.title_menu_5).setBackgroundResource(R.drawable.text_background);
		focusOnView();
		getData();
		//findViewById(R.id.title_menu_5).requestFocus();
	}
	public void onResume()
	{
		super.onResume();
		focusOnView();
	}
	private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
            	findViewById(R.id.title_scroll_view).scrollTo(findViewById(R.id.title_menu_5).getLeft(), 0);
            }
        });
    }
	public void getData()
    {
            images.clear();
            final ProgressDialog dialog = ProgressDialog.show(AutomobileActivity.this, null, 
                    getResources().getString(R.string.dialog_please_wait), true);
    
                    final Handler handler = new Handler() {
                       public void handleMessage(Message msg) {
                               //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
                    	   if(msg.what==1)
                    	   {
                        	   adapter=new ListAdapter(AutomobileActivity.this, titles, bodys, prices, images);
                        	   list.setAdapter(adapter);
                    	   }
                    	   else
                    		   Toast.makeText(AutomobileActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();

                           dialog.dismiss();
                          }
                       };
                    Thread checkUpdate = new Thread() {  
                       public void run() {
                               //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
                    	   if(network.isConnectedToServer(getResources().getString(R.string.json_car_url)+1, 5000) && network.isNetworkConnected())
                    	   {
                    		   JSONfuncObject main_json_data = new JSONfuncObject();
                               JSONObject json_data = main_json_data.getJSONfromURL(AutomobileActivity.this.getResources().getString(R.string.json_car_url)+1);
                               Log.d("TEST", "data="+json_data);
                                   try {
    								JSONArray id_array = json_data.getJSONArray("carzarid");
    								JSONArray factory_array = json_data.getJSONArray("carfactory");
    								JSONArray makedate_array = json_data.getJSONArray("carmakedate");
    								JSONArray orjirsen_array = json_data.getJSONArray("carorjirsen");
    								JSONArray price_array = json_data.getJSONArray("carprice");
    								JSONArray mark_array = json_data.getJSONArray("carmark");
    								JSONArray image_array = json_data.getJSONArray("carimage1");
    								
    								if(id_array.length()==10)
    	    						{
    	    							page+=1;
    	    							scrollable=true;
    	    						}
    	    						else
    	    						{
    	    							scrollable=false;
    	    						}
    								
    								for(int i=0;i<id_array.length();i++)
    								{
    									int temp_id=0;
    									for(int j=0;j<factory_keys.length;j++)
    									{
    										if(factory_keys[j]==factory_array.getInt(i))
    										{
    											temp_id=j;
    											break;
    										}
    									}
    									titles.add(orjirsen_array.getString(i)+" "+factory_names[temp_id]+" "+mark_array.getString(i));
    									ids.add(id_array.getInt(i));
    									bodys.add("Тайлбар");
    									prices.add(NumberFormat.getIntegerInstance().format(Long.parseLong(price_array.getString(i))));
    									images.add(AutomobileActivity.this.getResources().getString(R.string.json_car_image_url)+image_array.getString(i).split(",")[0]);
    								}
    							} catch (JSONException e) {
    								// TODO Auto-generated catch block
    								e.printStackTrace();
    							}
                                   handler.sendEmptyMessage(1); 
                    	   }
                    	   else
                    		   handler.sendEmptyMessage(0); 
                    	   
                          }
                       };
                    checkUpdate.start();
    }
	public void loadPageData(int page_number)
	{
        //final ProgressDialog dialog = ProgressDialog.show(AutomobileActivity.this, null, 
        //        getResources().getString(R.string.dialog_please_wait), true);

                final Handler handler = new Handler() {
                   public void handleMessage(Message msg) {
                           //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
                	   if(msg.what==1)
                	   {
                		   adapter.notifyDataSetChanged();
                    	   //adapter=new ListAdapter(AutomobileActivity.this, titles, bodys, prices, images);
                    	   //list.setAdapter(adapter);
                	   }
                	   else
                		   Toast.makeText(AutomobileActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
                	   progress.setVisibility(View.GONE);
             //          dialog.dismiss();
                      }
                   };
                Thread checkUpdate = new Thread() {  
                   public void run() {
                           //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
                	   if(network.isConnectedToServer(getResources().getString(R.string.json_car_url)+page, 5000) && network.isNetworkConnected())
                	   {
                		   JSONfuncObject main_json_data = new JSONfuncObject();
                           JSONObject json_data = main_json_data.getJSONfromURL(AutomobileActivity.this.getResources().getString(R.string.json_car_url)+page);
                           Log.d("TEST", "data="+json_data);
                               try {
								JSONArray id_array = json_data.getJSONArray("carzarid");
								JSONArray factory_array = json_data.getJSONArray("carfactory");
								JSONArray makedate_array = json_data.getJSONArray("carmakedate");
								JSONArray orjirsen_array = json_data.getJSONArray("carorjirsen");
								JSONArray price_array = json_data.getJSONArray("carprice");
								JSONArray mark_array = json_data.getJSONArray("carmark");
								JSONArray image_array = json_data.getJSONArray("carimage1");
								if(id_array.length()==10)
	    						{
	    							page+=1;
	    							scrollable=true;
	    						}
	    						else
	    						{
	    							scrollable=false;
	    						}
								for(int i=0;i<id_array.length();i++)
								{
									int temp_id=0;
									for(int j=0;j<factory_keys.length;j++)
									{
										if(factory_keys[j]==factory_array.getInt(i))
										{
											temp_id=j;
											break;
										}
									}
									titles.add(orjirsen_array.getString(i)+" "+factory_names[temp_id]+" "+mark_array.getString(i));
									ids.add(id_array.getInt(i));
									bodys.add("Тайлбар");
									prices.add(NumberFormat.getIntegerInstance().format(Long.parseLong(price_array.getString(i))));
									images.add(AutomobileActivity.this.getResources().getString(R.string.json_car_image_url)+image_array.getString(i).split(",")[0]);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
                               handler.sendEmptyMessage(1); 
                	   }
                	   else
                		   handler.sendEmptyMessage(0); 
                	   
                      }
                   };
                checkUpdate.start();
	}
	public void createTitleComponents() {
		// Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
		
		// Үндсэн товчлууруудын үйлдэл
		// Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		// Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(AutomobileActivity.this, ItemActivityFromDB.class));
						overridePendingTransition(R.anim.top_in, R.anim.no_anim);
					}
				});
		// Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(AutomobileActivity.this, SearchActivity.class));
						overridePendingTransition(R.anim.top_in, R.anim.no_anim);
					}
				});
		// Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(AutomobileActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		// Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});

		// Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutomobileActivity.this, MainActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutomobileActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutomobileActivity.this, NewApartmentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutomobileActivity.this, UBActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent(AutomobileActivity.this, AutomobileActivity.class); 
//				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
//				startActivity(intent);
			}
		});
	}
}
